<template>
	<a-modal v-model='showModal' @ok='confirmOk' @cancel='cancel' :title='titles' width='70%'>
		<a-spin :spinning='loading'>
			<a-form :form='form'>
				<a-row :gutter='[24, 0]'>
					<a-col :span='12'>
						<a-form-item class='mb-15' label='商品名称' :label-col='labelCol' :wrapper-col='wrapperCol'>
							<a-input placeholder='请输入'
								v-decorator="['name', { rules: [{ required: true, message: '请输入', whitespace: true }] }]"
								maxLength='30'></a-input>
						</a-form-item>
					</a-col>
					<a-col :span='12'>
						<a-form-item class='mb-15' label='商品图片(最多上传8张)' :label-col='labelCol' :wrapper-col='wrapperCol'>
							<PreviewImage :showUpload='isShow' class='mt-12' :is-preview='false' :scene='1'
								:show-upload='formgetFileLength(`picUrl`) < 1'
								@uploadSuccess='formuploadSuccess($event, `picUrl`)' accept=".png,.jpg" v-decorator="[
									`picUrl`,
									{
										rules: [{ required: true, message: '请上传图片', type: 'array' }],
										initialValue: [],
									},

								]" :maxCount='1' />
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter='[24, 0]'>
					<a-col :span='12'>
						<a-form-item class='mb-15' label='商品分类' :label-col='labelCol' :wrapper-col='wrapperCol'>
							<div class='flex'>
								<div style='width:48%'>
									<a-select class='flex-1' @change='changeSelect' placeholder='请选择'
										v-decorator="['firstCategoryId', { rules: [{ required: true, message: '请选择' }] }]">
										<a-select-option :value='item.id' v-for='(item, index) in class_list'
											:key='index'>{{ item.name }}
										</a-select-option>
									</a-select>

								</div>
								<div style='width:48%;margin-left: 4%'>
									<a-select class='flex-1' placeholder='请选择'
										v-decorator="['secondCategoryId', { rules: [{ required: true, message: '请选择' }] }]">
										<a-select-option :value='item.id' v-for='(item, index) in class_list2'
											:key='index'>{{ item.name }}
										</a-select-option>
									</a-select>
								</div>
							</div>
						</a-form-item>
					</a-col>
					<a-col :span='12'>
						<a-form-item class='mb-15' label='所属店铺' :label-col='{ span: 4 }' :wrapper-col='{ span: 20 }'>
							<a-select v-decorator="[

								'storeId',
								{
									rules: [{ required: true, message: '请输入', whitespace: true, type: 'number' }],
								},

							]">
								<a-select-option :value='item.id' v-for='(item, index) in store_list' :key='index'>{{
									item.name }}
								</a-select-option>
							</a-select>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter='[24]'>
					<a-col :span='12'>
						<a-form-item class='mb-15' label='库存单位' :label-col='labelCol' :wrapper-col='wrapperCol'>
							<a-select v-decorator="[

								'unit',
								{
									rules: [{ required: true, message: '请输入', whitespace: true }]
								}
							]">
								<a-select-option :value='item.value' v-for='(item, index) in unitList' :key='index'>{{
									item.label }}
								</a-select-option>
							</a-select>


						</a-form-item>
					</a-col>
					<a-col :span='12'>
						<a-form-item class='mb-15' label='运费' :label-col='labelCol' :wrapper-col='wrapperCol'>
							<a-input placeholder='请输入' v-decorator="[

								'freight',
								{
									rules: [{ required: true, message: '请输入', whitespace: true }],
								},

							]" maxLength='30' suffix="元"></a-input>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter='24'>
					<a-col :span='24'>
						<a-form-item class='mb-15' label='商品简介' :label-col='{ span: 4 }' :wrapper-col='{ span: 20 }'>
							<a-textarea placeholder='请输入' v-decorator="[

								'introduction',
								{
									rules: [{ required: true, message: '请输入', whitespace: true }],
								},
							]" maxLength='300'></a-textarea>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter='[24, 0]'>
					<a-col :span='12'>
						<!-- <a-form-item class='mb-15' label='商品宣传视频' :label-col='labelCol' :wrapper-col='wrapperCol'>
              <PreviewImage :showUpload='isShow' class='mt-12' :is-preview='false' :scene='8'
                            :show-upload='formgetFileLength(`videoUrl`) < 1'
                            @uploadSuccess='formuploadSuccess($event, `videoUrl`)' v-decorator="[

                  `videoUrl`,
                  {
                    rules: [{ required: true, message: '请上传', type: 'array' }],
                    initialValue: []
                  }
                ]" />

            </a-form-item> -->

						<a-form-item class='mb-15' label='商品宣传视频' :label-col='labelCol' :wrapper-col='wrapperCol'>
							<a-upload @change='videoChange' :before-upload='beforeUpload' :showUploadList='false'
								action='http://cwqd.ricecs.cn/admin-api/system/file/upload'
								:headers='{ Authorization: token }' accept=".mp4">
								<a-button>
									<a-icon type='upload' />
									上传
								</a-button>
							</a-upload>
							<!--              <video-player
                class='video-player vjs-custom-skin'
                ref='videoPlayer'
                :options='playerOptions'
              ></video-player>-->
							<video :src='videoUrl' style='width: 100%;height: 120px' controls></video>
						</a-form-item>
					</a-col>
					<a-col :span='12'>
						<a-form-item class='mb-15' label='状态' :label-col='labelCol' :wrapper-col='wrapperCol'>
							<a-switch checked-children='已上架' un-checked-children='未上架'
								v-decorator="['status', { valuePropName: 'checked' }]" />
						</a-form-item>
					</a-col>
				</a-row>
				<div class='flex justify-between'>
					<div>商品规格：</div>
					<a-button type='primary' @click='handleAdd'>添加</a-button>
				</div>
				<a-row :gutter='24'>
					<a-col :span='24'>
						<a-table class='mt-16 order-table' :columns='columns' :data-source='dataSource'
							:pagination='false'>
							<template #name='name, data, index'>
								<a-input v-model='data.name' placeholder='请输入' v-if='index == tabIndex' />
								<div v-else>{{ data.name }}</div>
							</template>
							<template #picUrl='picUrl, data, index'>
								<div class='flex items-center justify-center'>
									<a-upload v-if='index == tabIndex' list-type='picture-card' class='avatar-uploader'
										:show-upload-list='false'
										action='http://cwqd.ricecs.cn/admin-api/system/file/upload'
										:headers='{ Authorization: token }' @change='handleImg' accept=".png,.jpg">
										<img v-if='picUrl' style='width: 102.88px; height: 102.88px' :src='picUrl'
											alt='avatar' />
										<div v-else>
											<a-icon :type="loading ? 'loading' : 'plus'" />
											<div class='ant-upload-text'>Upload</div>
										</div>
									</a-upload>
									<img :src='picUrl' style='width: 102.88px; height: 102.88px' alt='avatar'
										v-if='tabIndex != index && picUrl' />
								</div>
							</template>
							<template #stock='stock, data, index'>
								<a-input v-model='data.stock' placeholder='请输入' v-if='index == tabIndex' />
								<div v-else>{{ data.stock }}</div>
							</template>
							<template #price='price, data, index'>
								<a-input v-model='data.price' placeholder='请输入' v-if='index == tabIndex' />
								<div v-else>{{ data.price }}</div>
							</template>
							<template #costPrice='costPrice, data, index'>
								<a-input v-model='data.costPrice' placeholder='请输入' v-if='index == tabIndex' />
								<div v-else>{{ data.costPrice }}</div>
							</template>
							<template v-if="isfrom === 'newPeopleGoods'"
								#newCustomerStock='newCustomerStock, data, index'>
								<a-input v-model='data.newCustomerStock' placeholder='请输入' v-if="index == tabIndex" />
								<div v-else>{{ data.newCustomerStock }}</div>
							</template>

							<template v-if="isfrom === 'newPeopleGoods'"
								#newCustomerPrice='newCustomerPrice, data, index'>
								<a-input v-model='data.newCustomerPrice' placeholder='请输入' v-if="index == tabIndex" />
								<div v-else>{{ data.newCustomerPrice }}</div>
							</template>
							<template v-if="isfrom === 'oldPeopleGoods'"
								#existedCustomerStock='existedCustomerStock, data, index'>
								<a-input v-model='data.existedCustomerStock' placeholder='请输入'
									v-if="index == tabIndex" />
								<div v-else>{{ data.existedCustomerStock }}</div>
							</template>

							<template v-if="isfrom === 'oldPeopleGoods'"
								#existedCustomerPrice='existedCustomerPrice, data, index'>
								<a-input v-model='data.existedCustomerPrice' placeholder='请输入'
									v-if="index == tabIndex" />
								<div v-else>{{ data.existedCustomerPrice }}</div>
							</template>
							<template #action='action, data, index'>
								<div class='flex items-center justify-center'>
									<a-button @click='onDelete(index)' class='ml-10 mr-10' type='danger'> 删除</a-button>
									<a-button @click='handleChange(index)' class='mr-10' type='primary'
										style='background: #32cd32'>
										编辑
									</a-button>
								</div>
							</template>
						</a-table>
					</a-col>
				</a-row>
				<div class='mt-20 mb-20'>产品详情：</div>
				<a-row :gutter='24'>
					<a-col :span='24'>
						<quill-editor class='editor' v-model='content' ref='myQuillEditor' :options='editorOption'
							@blur='onEditorBlur($event)' @focus='onEditorFocus($event)' @change='onEditorChange($event)'
							@ready='onEditorReady($event)'>
						</quill-editor>
					</a-col>
				</a-row>
			</a-form>
		</a-spin>
	</a-modal>
</template>
<script>
import {
	quillEditor
} from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import {
	get
} from 'lodash'
import {
	getSpuCreate,
	getSpuUpdate,
	productList,
	getStoreList,
	getSpugetdetail
} from '@/api/newPet'
import {
	dictData
} from '@/api/index'
import storage from '@/utils/storage'
import {
	ACCESS_TOKEN
} from '@/store/mutation-types'
// 在main.js中全局引入
import VideoPlayer from 'vue-video-player/src'
import 'vue-video-player/src/custom-theme.css'
import 'video.js/dist/video-js.css'

export default {
	props: ['type', 'isfrom'],
	components: {
		VideoPlayer
	},
	data() {
		return {
			loading: false,
			isShow: true,
			labelCol: {
				span: 8
			},
			unitList: [],
			content: '',
			editorOption: {
				placeholder: '请输入',
				theme: 'snow',
				modules: {
					toolbar: {
						container: [
							['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
							['blockquote', 'code-block'], // 引用  代码块
							[{
								header: 1
							},
							{
								header: 2
							}
							], // 1、2 级标题
							[{
								list: 'ordered'
							},
							{
								list: 'bullet'
							}
							], // 有序、无序列表
							[{
								script: 'sub'
							},
							{
								script: 'super'
							}
							], // 上标/下标
							[{
								indent: '-1'
							},
							{
								indent: '+1'
							}
							], // 缩进
							// [{ direction: 'rtl' }], // 文本方向
							[{
								size: ['12', '14', '16', '18', '20', '22', '24', '28', '32', '36']
							}], // 字体大小
							[{
								header: [1, 2, 3, 4, 5, 6]
							}], // 标题
							[{
								color: []
							},
							{
								background: []
							}
							], // 字体颜色、字体背景颜色
							// [{ font: ['songti'] }], // 字体种类
							[{
								align: []
							}], // 对齐方式
							['clean'], // 清除文本格式
							['image'] // 链接、图片，需要视频的可以加上video
						]
					}
				}
			},
			count: 1,
			dataSource: [],
			columns: [{
				title: '规格名称',
				dataIndex: 'name',
				align: 'center',
				width: 140,
				scopedSlots: {
					customRender: 'name'
				}
			},
			{
				title: '规格图片',
				dataIndex: 'picUrl',
				width: 120,
				align: 'center',
				scopedSlots: {
					customRender: 'picUrl'
				}
			},
			{
				title: '规格库存',
				dataIndex: 'stock',
				align: 'center',
				width: 70,
				scopedSlots: {
					customRender: 'stock'
				}
			},
			{
				title: '规格价格（元）',
				dataIndex: 'price',
				align: 'center',
				width: 70,
				scopedSlots: {
					customRender: 'price'
				}
			},
			{
				title: '成本价格',
				dataIndex: 'costPrice',
				align: 'center',
				width: 70,
				scopedSlots: {
					customRender: 'costPrice'
				}
			},
			{
				title: '操作',

				dataIndex: 'action',
				width: 160,
				scopedSlots: {
					customRender: 'action'
				},
				align: 'center'
			}
			],

			wrapperCol: {
				span: 16
			},
			details: {},
			showModal: false,
			titles: '新增',
			info: {
				name: '123'
			},
			form: this.$form.createForm(this),
			class_list: [],
			class_list2: [],
			tabIndex: -1,
			token: '',
			store_list: [],
			videoUrl: ''
		}
	},
	computed: {},
	watch: {},
	async created() {
		this.token = storage.get(ACCESS_TOKEN)
		this.get_store()
	},
	components: {
		quillEditor
	},
	methods: {
		beforeUpload(file) {
			console.log(file)
			const isLt500KB = file.size / 1024 / 1024 < 100
			let isVideo = true
			if (!isLt500KB) {
				this.$message.error('上传的文件大小不能超过 100mb!')
				return false
			}
			if (file.type != 'video/mp4') {
				this.$message.error('请上传视频文件')
				return false
			}
			return true
		},
		async get_store() {
			const res2 = await dictData({
				type: 'product_unit'
			})
			this.unitList = res2
			getStoreList({
				pageNo: 1,
				pageSize: 100
				// type: 0,
				// status: 1,
				// name: ''
			}).then((res) => {
				this.store_list = res.list
			})
		},
		handleImg(info) {
			let fileList = [...info.fileList]
			// 2. read from response and show file link
			fileList = fileList.map((file) => {
				if (file.response) {
					this.dataSource[this.tabIndex].picUrl = file.response.data
				}
				return file
			})
		},
		handleChange(index) {
			this.tabIndex = index
		},
		handleAdd() {
			const {
				dataSource,
				count
			} = this
			const newData = {
				name: `规格 ${count}`,
				key: count,
				picUrl: '',
				stock: '',
				price: '',
				costPrice: ''
			}
			this.count = count + 1
			this.dataSource = [...dataSource, newData]
			console.log(this.dataSource, 'xxx')
		},
		onDelete(key) {
			this.tabIndex = -1
			this.dataSource.splice(key, 1)
		},
		onEditorBlur(quill) {
			console.log('editor blur!', quill)
		},
		// 获得焦点事件
		onEditorFocus(quill) {
			console.log('editor focus!', quill)
		},
		// 准备富文本编辑器
		onEditorReady(quill) {
			console.log('editor ready!', quill)
		},
		// 内容改变事件，只需要这一个方法就够了
		onEditorChange({
			quill,
			html,
			text
		}) {
			console.log('editor change!', quill, html, text)
			this.content = html
		},
		getFormgetFileLength(type) {
			return get(type, 'length') || 0
		},
		formgetFileLength(type) {
			//获取图片
			return get(this.form.getFieldValue(type), 'length') || 0
		},
		getormuploadSuccess(data, item) {
			item.picUrl = [...item.picUrl, data.path]
		},
		formuploadSuccess(data, type) {
			if (this.form.getFieldValue(type).length < 8) {
				this.form.setFieldsValue({
					[type]: [...this.form.getFieldValue(type), data.path]
				})
			} else {
				this.$message.error('最多上传8张图片')
			}
		},
		formuploadSuccess2(data, type, index) {
			this.dataSource[index].picUrl = data.path
		},
		async changeSelect(e) {
			console.log(e, 'changeSelect')
			this.form.setFieldsValue({
				secondCategoryId: ''
			})
			this.class_list2 = await this.get_class2(e)
		},
		onChange(e) {
			console.log(e.target.value)
		},
		cancel() {
			this.form.resetFields()
			this.showModal = false
			this.tabIndex = -1
		},
		confirmOk() {
			this.form.validateFields((err, values) => {
				if (!err) {
					// this.loading = true
					const {
						info
					} = this
					let skus = this.dataSource
					skus.forEach((item) => {
						if (Array.isArray(item.picUrl)) {
							item.picUrl = item.picUrl.join(', ') // 将数组转换为以逗号分隔的字符串
						}
					})
					let data = {
						id: info && info.id ? info.id : undefined,
						...this.$utils.trimValue(values),
						status: typeof values.status === 'undefined' ? 0 : values.status ? 1 : 0,
						skus: skus,
						description: this.content,
						// storeId: this.info.storeId,
						deliveryTemplateId: this.info.deliveryTemplateId
					}
					data.type = this.type
					data.picUrl = data.picUrl.toString()
					data.videoUrl = this.videoUrl
					data.newCustomerPrice = values.newCustomerPrice ? values.newCustomerPrice / 100 : ''
					data.existedCustomerPrice = values.existedCustomerPrice ? values.existedCustomerPrice /
						100 : ''
					// data.videoUrl = data.videoUrl.toString()
					const fun = info && info.id ? getSpuUpdate : getSpuCreate
					fun(data)
						.then(() => {
							this.$message.success(info && info.id ? '修改成功！' : '新增成功！')
							this.$emit('upload')
							this.cancel()
						})
						.finally(() => {
							this.loading = false
						})
				}
			})
		},
		getData() {
			this.loading = true
			deductionDetail({
				id: 1
			})
				.then((data) => {
					this.details = data
				})
				.finally(() => (this.loading = false))
		},
		async open(data) {
			this.info = data
			if (data.id) {
				this.titles = '修改'
				this.class_list = await this.get_class(this.type)
				this.class_list2 = await this.get_class2(data.firstCategoryId)
				const res = await getSpugetdetail({
					id: data.id
				})
				this.dataSource = res.skus ? res.skus : []
			} else {
				this.titles = '新增'
				this.class_list = await this.get_class(this.type)
				this.dataSource = []
			}

			this.showModal = true
			this.content = data.description
			// 在赋值之后添加一下代码就可以了
			const w = window
			const screenWidth = w.document.documentElement.clientWidth
			const screenHeight = w.document.documentElement.clientHeight
			this.playerOptions = {
				height: '200px',
				width: '100%',
				playsinline: true,
				autoplay: false, // 如果true,浏览器准备好时开始回放。
				muted: true, // 默认情况下将会消除任何音频。
				loop: false, // 导致视频一结束就重新开始。
				preload: 'auto', // 建议浏览器在<video>加载分素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
				language: 'zh-CN', //aspectRatio: screenWidth + ':' + screenHeight, // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3")
				fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
				sources: [{
					type: 'video/mp4', // 这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
					src: data.videoUrl // url地址
				}],
				poster: data.videoUrl +
					'?vframe/jpg/offset/1', // 你的封面地址。?vframe/jpg/offset/1添加的七牛参数，截取视频首屏作为封面；
				controlBar: {
					timeDivider: true,
					durationDisplay: true,
					remainingTimeDisplay: false,
					fullscreenToggle: false // 全屏按钮
				}
			}
			this.$nextTick(() => {
				this.form.setFieldsValue({
					isEnabled: true,
					...data,

					picUrl: data.picUrl.split(','),
					videoUrl: data.videoUrl.split(','),
					unit: data.unit.toString(),
					freight: data.freight.toString()
				})
			})
		},
		//视频
		videoChange(info) {
			console.log(info)
			let _this = this
			let fileList = [...info.fileList]

			// 1. Limit the number of uploaded files
			//    Only to show two recent uploaded files, and old ones will be replaced by the new
			fileList = fileList.slice(-1)

			// 2. read from response and show file link
			fileList = fileList.map((file) => {
				if (file.response) {
					// Component will show file.url as link
					_this.videoUrl = file.response.data
				}
			})
		},

		// 分类列表
		get_class(id) {
			return new Promise((resolve) => {
				productList({
					type: 0,
					spuType: this.type,
					parentId: 0
				}).then((res) => {
					resolve(res)
				})
			})
		},
		// 二级分类
		get_class2(id) {
			console.log(id)
			return new Promise((resolve) => {
				productList({
					type: 0,
					spuType: this.type,
					parentId: id
				}).then((res) => {
					resolve(res)
				})
			})
		}

	}
}
</script>
<style lang='less' scoped>
/deep/ .ant-form-item-label {
	// width: 100px;
}

/deep/ .ant-upload-picture-card-wrapper {
	display: flex;
	justify-content: center;
}
</style>